<?php

namespace douyin;

use think\exception\ValidateException;
use think\facade\Config;

class DouyinUtil
{
    public static function jscode2session($dy_app, $code){

        $post = [
            'appid' => Config::get('douyin.' . $dy_app . '.appid', ''),
            'secret' => Config::get('douyin.' . $dy_app . '.secret', ''),
            'code' => $code,
        ];

        $client = new \GuzzleHttp\Client();
        $ret = $client->request('POST', 'https://developer.toutiao.com/api/apps/v2/jscode2session', [
            'json' => $post,
        ]);

        if (200 != $ret->getStatusCode()) {
            throw new ValidateException('抖音服务器响应码错误');
        }

        $data = json_decode($ret->getBody(), true);
        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new ValidateException('抖音服务器响应格式错误');
        }

        return $data;
    }
}